/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package qrlogin;

/**
 *
 * @author adee
 */
public class QRLoginJQueryLoginChecker {
    private QRLoginServlet servlet;
    public QRLoginJQueryLoginChecker(QRLoginServlet servlet) {
        this.servlet = servlet;
    }
    public String getLoginer(){
        StringBuilder builder = new StringBuilder();
        builder.append("\n<script type= \"text/javascript\">\n");
        builder.append(
            "function checkerMainLoop(){"+
               "$.get('%%LoginLink%%?op=GET_COMMAND', function(data) {"+
                  "if (data=='LOGIN') {"+
                  "  window.location.href='%%SecuredPage%%'"+
                  " }"+
                  "if (data=='LOGOUT') {"+
                  "  window.location.href='%%MainPage%%'"+
                  " }"+
                  "if (data=='KEEP_ALIVE') {"+
                  "setTimeout('checkerMainLoop()',%%Interval%%);"+
                  " }"+
               "});"+
            "}"+
            "$(function (){"+
                "checkerMainLoop();"+
               "});" );
        builder.append("</script>\n");
        String servletName = this.servlet.getServletParameters().getLoginLink().substring(
                this.servlet.getServletParameters().getLoginLink().lastIndexOf("/"));
        return builder.toString()
                .replace("%%LoginLink%%",this.servlet.getServletParameters().getContextPath()+servletName)
                .replace("%%Interval%%", String.valueOf(this.servlet.getServletParameters().getClientCheckInterval()))
                .replace("%%SecuredPage%%", this.servlet.getServletParameters().getSecuredPage())
                .replace("%%MainPage%%",this.servlet.getServletParameters().getMainPage());
    }

}
